var Default = require("Default.js");
var common = require("common.js");
const login={};
login.getSystemInfo=function(){
  let systeminfo=wx.getStorageSync('systeminfo');
  if(!systeminfo){
    try {
      systeminfo = wx.getSystemInfoSync()
      wx.getNetworkType({
        success: function(res) {
          systeminfo.networkType = res.networkType
          systeminfo=JSON.stringify(systeminfo)
          wx.setStorageSync('systeminfo',systeminfo)
          return systeminfo;
        }
      })
    } catch (e) {
    }
  }else{
    return systeminfo;
  }
}
login.post = function (url, parm,data) {
  console.warn("URL:", url, "parms:", parm);
  //限制同一时间只有一个登录验证请求
  if(wx.loginOnoff){
    return new Promise(function(success,fail){

    })
  }
  wx.loginOnoff=true;
  const time=new Date().getTime();
  const systeminfo=login.getSystemInfo();
  console.log(systeminfo)
  return new Promise(function (success, fail) {
    wx.request({
      url: url,
      data: parm,
      method: "POST",
      header: {
        'content-type': 'application/json',
        'From':'xqx_c_wxxcx',
        'DateTime':time,
        'TerminalEnv':systeminfo
      },
      success: function (res) {
        wx.loginOnoff=false;
        console.log(res);
        res.data.token&&wx.setStorageSync('token',res.data.token)
        if(res.data.needRegister){
          console.warn('其他接口访问，经重新登录接口再次验证需要跳转手机号页面注册');
          const path=getCurrentPages()[0].route;
          if(path.indexOf('boundNumber/boundNumber')==-1&&!data){
            wx.navigateTo({
              url: '/pages/boundNumber/boundNumber'
            })
          }else if(data){
            success(res.data);
          }
        }else{
          success(res.data);
        }
      },
      fail: function (error) {
        wx.loginOnoff=false;
        fail(error)
      }
    })
  });
}
login.get3rdSessionV2 = function (parm,data) {
  return login
    .post(Default.HOST + Default.GET_3RD_SESSIONV2, parm || {},data);
}
login.login = function (data,flag) {
  return new Promise(function (success, fail) {
    wx.login({
      success: function (res) {
        console.log(res);
        var code = res.code;
        wx.getUserInfo({
          withCredentials:true,
          success: function (res) {
            const reqdata=flag?{ code: code, encryptedData: res.encryptedData, iv: res.iv ,payFlag:'log'}:{ code: code, encryptedData: res.encryptedData, iv: res.iv };
            login.get3rdSessionV2(reqdata,data).then(function (result) {
              success(result);
            }).catch(function (error) {
              console.log(error);
              fail(error);
            });
          },
          fail: function (err) {
            wx.showModal({
              title: '温馨提示',
              cancelText: '拒绝授权',
              confirmText: '同意授权',
              content:'很遗憾，因为授权失败，您将无法正常使用小程序。请到设置里（右上角 - 关于 - 右上角 - 设置）重新授权。',
              success: function (res) {
                if (res.confirm) {
                  wx.openSetting({
                    success: function (res) {
                      if (res.authSetting["scope.userInfo"]) {
                        //执行重新获取用户信息
                        wx.getUserInfo({
                          success: function (res) {
                            const reqdata=flag?{ code: code, encryptedData: res.encryptedData, iv: res.iv ,payFlag:'log'}:{ code: code, encryptedData: res.encryptedData, iv: res.iv };
                            login.get3rdSessionV2(reqdata,data).then(function (result) {
                              console.log(result);
                              success(result);
                            }).catch(function (error) {
                              console.log(error);
                              fail(error);
                            });
                          }
                        })
                      } else {

                      }
                    }
                  })
                }
              }
            })

          }
        })


      }
    });
  })

}
module.exports = login;
